package genetic.selection;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Random;

import genetic.interfaces.Individual;
import genetic.interfaces.Population;
import genetic.interfaces.Selection;

public class MarioSelectionTournament<Fitness extends Number & Comparable<Fitness>, I extends Individual<?, Fitness>> implements Selection<I> {

	private Population<I> pop;
	private Random random;
	
	public MarioSelectionTournament(Population<I> pop) {
		this.pop = pop;
		random = new Random();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public I[] select() {
		ArrayList<I> parents = new ArrayList<I>();
		int t1, t2, t3, t4;
		I individuals[] = pop.getIndividuals();
		t1 = random.nextInt(individuals.length);
		do{
			t2 = random.nextInt(individuals.length);
		}while(t2 == t1);
		
		do{
			t3 = random.nextInt(individuals.length);
		}while(t3 == t1 || t3 == t2);
		do{
			t4 = random.nextInt(individuals.length);
		}while(t4 == t3 || t4 == t2 || t4 == t1);
		
		if(individuals[t1].eval().compareTo(individuals[t2].eval()) > 0){
			parents.add(individuals[t1]);
		}else{
			parents.add(individuals[t2]);
		}
		
		if(individuals[t3].eval().compareTo(individuals[t4].eval()) > 0){
			parents.add(individuals[t3]);
		}else{
			parents.add(individuals[t4]);
		}
		
		return (I[]) parents.toArray( (I[]) Array.newInstance(parents.get(0).getClass(), parents.size()));
	}

}
